package com.woldier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woldier.common.BaseContext;
import com.woldier.dto.OrdersDto;
import com.woldier.entity.*;
import com.woldier.mapper.OrderMapper;
import com.woldier.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl
        extends ServiceImpl<OrderMapper, Orders>
        implements OrderService {


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    /*保存order 以及详细信息*/
    @Override
    @Transactional /*开启事务*/
    public void saveWithDetail(Orders orders) {
        /*user_id create_time checkout_time amount的设置*/
        setOrderInfo(orders);

        /*查询送餐冗余信息 保存到order中*/
        setInfo(orders);

        /*保存order*/
        this.save(orders);



        /*保存order详细信息*/
            /*1.获取购物车数据*/
        List<ShoppingCart> shoppingCartList = shoppingCartService.getByUid(orders.getUserId());
            /*2.保存订单详细信息*/
            /*将购物车对象封装成orderDetail对象*/
        BigDecimal amount = BigDecimal.ZERO; /*保存总价*/
        Long id = orders.getId();/*获取order的id*/
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            /*new一个orderDetail实体进行封装*/
            OrderDetail orderDetail = new OrderDetail();
            /*通过对象深度拷贝 拷贝对应属性*/
            BeanUtils.copyProperties(shoppingCart,orderDetail,"id");
            /*传入order_id*/
            orderDetail.setOrderId(id);
            orderDetailList.add(orderDetail); /*添加到集合中*/
            amount = amount.add(shoppingCart.getAmount()); /*累计总价*/
            /*清除购物车*/
            shoppingCartService.removeById(shoppingCart.getId());
        }
            /*保存*/
        orderDetailsService.saveBatch(orderDetailList);
            /*更新order的amount字段信息*/
        orders.setAmount(amount);
        orders.setNumber(orders.getId().toString());
        this.updateById(orders);

    }


    /**
     *
     * 获取订单详情
     * @return
     */

    @Override
    public Page<OrdersDto> getOrderWithDetails(int page , int pageSize) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page,pageSize);

        /*查询到所有的订单*/
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        /*若现在的id为用户id 则更具用户id查询*/
        lambdaQueryWrapper.eq(BaseContext.getCurrentId()!=1,Orders::getUserId,BaseContext.getCurrentId());
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        /*查询数据库 SELECT * FROM orders WHERE user_id = ?*/
        this.page(ordersPage,lambdaQueryWrapper);


        /*得出其中的records*/
        List<Orders> orders = ordersPage.getRecords();
        /*dto list*/
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        /*查询详细订单*/
        /*遍历orders 查询其中的订单详情*/
        for (Orders order : orders) {
            OrdersDto ordersDto = new OrdersDto();
            /*对象拷贝*/
            BeanUtils.copyProperties(order,ordersDto);
            /*根据order_id查询 details*/
            LambdaQueryWrapper <OrderDetail>  queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(OrderDetail::getOrderId,order.getId());
            /*SELECT * FROM orderDetail WHERE order_id = ?*/
            List<OrderDetail> list = orderDetailsService.list(queryWrapper);

            /*将结果设置给dto*/
            ordersDto.setOrderDetails(list);

            /*ordersDto 加入list中*/
            ordersDtoList.add(ordersDto);
        }
        /*拷贝page 忽略records*/
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtoList);
        return ordersDtoPage;
    }


    /*----------------------------------------*/
    private void setOrderInfo(Orders orders){
        /*user_id create_time checkout_time amount的设置*/
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(BigDecimal.ZERO);
    }

    private void setInfo(Orders orders){
        /*查询送餐冗余信息 保存到order中*/
        /*根据id查询数据库*/
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        User user = userService.getById(orders.getUserId());
        /*信息设置到order中*/
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
    }
}
